package com.project.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import javafx.scene.transform.Affine;

/**
 * 图片上传
 * 
 * @author gxs
 *
 */
public class Fileupload {

	// 检测是否是多媒体上传
	// public boolean isMultipartContent(HttpServletRequest request){
	// }
	public static void copy() {
		try {

		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 重构在数据库中的存储路径
	 * @param picturesFileName
	 * @param savePath
	 * @return
	 */
	public static List<String> getLocalPaths(List<String> picturesFileName, String savePath ) {
		// TODO Auto-generated method stub
		List<String> result = new ArrayList<String>();
		for (int i = 0; i < picturesFileName.size(); i++) {
			result.add(savePath + Fileupload.fileNameType(picturesFileName.get(i)));
		}
		return result;
	}
	/**
	 * 图片上传
	 * @param dir 存放文件夹
	 * @param pictures  图片
	 * @param picturesFileName  图片名称
	 * @return
	 */
	public static String uploadFiles(String dir, List<File> pictures, List<String> picturesFileName){
		HttpServletRequest request = ServletActionContext.getRequest();
		String webPath = "upload/";
		for(int i=0; i<pictures.size(); i++){
			uploadFile(pictures.get(i), dir, picturesFileName.get(i));
		}
		return StringUtil.SUCCESS;
	}
	
	public static void uploadFile(File file, String dir, String picturesFileName) {
		// TODO Auto-generated method stub
		try {
			InputStream inputStream = new FileInputStream(file);
//			String dir = ServletActionContext.getRequest().getRealPath("/")+ StringUtil.F_SAVE_DIRECTORY;
			File fileLocation = new File(dir);
			if(!fileLocation.exists()){
				boolean isCreate = fileLocation.mkdirs();
				if (!isCreate) {
					System.out.println(StringUtil.FAILURE);
				}
			}
			String fileName = Fileupload.fileNameType(picturesFileName);
			File uploadFile = new File(dir, fileName);		//文件路径和文件名
			OutputStream outputStream = new FileOutputStream(uploadFile);
			byte[] buffer = new byte[1024*1024];
			int length;
			while ((length = inputStream.read(buffer))>0) {
				outputStream.write(buffer, 0, length);
			}
			inputStream.close();
			outputStream.close();
			//处理图片
			String src = dir + fileName;
			String result = dir+ fileName;
			Fileupload.scale(src, result, "JPEG", StringUtil.HEIGHT, StringUtil.WIDTH, false);	//统一长度、宽度
		} catch (FileNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	
	/**
    * 删除文件，可以是文件或文件夹
    *
    * @param fileName
    *            要删除的文件名
    * @return 删除成功返回true，否则返回false
    */
   public static boolean delete(String fileName) {
       File file = new File(fileName);
       if (!file.exists()) {
           System.out.println("删除文件失败:" + fileName + "不存在！");
           return false;
       } else {
           if (file.isFile())
               return deleteFile(fileName);
           else
               return deleteDirectory(fileName);
       }
   }

   /**
    * 删除单个文件
    *
    * @param fileName
    *            要删除的文件的文件名
    * @return 单个文件删除成功返回true，否则返回false
    */
   public static boolean deleteFile(String fileName) {
       File file = new File(fileName);
       // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
       if (file.exists() && file.isFile()) {
           if (file.delete()) {
               System.out.println("删除单个文件" + fileName + "成功！");
               return true;
           } else {
               System.out.println("删除单个文件" + fileName + "失败！");
               return false;
           }
       } else {
           System.out.println("删除单个文件失败：" + fileName + "不存在！");
           return false;
       }
   }

   /**
    * 删除目录及目录下的文件
    *
    * @param dir
    *            要删除的目录的文件路径
    * @return 目录删除成功返回true，否则返回false
    */
   public static boolean deleteDirectory(String dir) {
       // 如果dir不以文件分隔符结尾，自动添加文件分隔符
       if (!dir.endsWith(File.separator))
           dir = dir + File.separator;
       File dirFile = new File(dir);
       // 如果dir对应的文件不存在，或者不是一个目录，则退出
       if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
           System.out.println("删除目录失败：" + dir + "不存在！");
           return false;
       }
       boolean flag = true;
       // 删除文件夹中的所有文件包括子目录
       File[] files = dirFile.listFiles();
       for (int i = 0; i < files.length; i++) {
           // 删除子文件
           if (files[i].isFile()) {
               flag = deleteFile(files[i].getAbsolutePath());
               if (!flag)
                   break;
           }
           // 删除子目录
           else if (files[i].isDirectory()) {
               flag = deleteDirectory(files[i]
                       .getAbsolutePath());
               if (!flag)
                   break;
           }
       }
       if (!flag) {
           System.out.println("删除目录失败！");
           return false;
       }
       // 删除当前目录
       if (dirFile.delete()) {
           System.out.println("删除目录" + dir + "成功！");
           return true;
       } else {
           return false;
       }
   }
	/**
	 * 缩放图像（按比例缩放）
	 * 
	 * @param srcImageFile
	 *            源图像文件地址
	 * @param result
	 *            缩放后的图像地址
	 * @param scale
	 *            缩放比例
	 * @param flag
	 *            缩放选择:true 放大; false 缩小;
	 */
	public final static void scale(String srcImageFile, String result, int scale, boolean flag) {
		try {
			BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
			int width = src.getWidth(); // 得到源图宽
			int height = src.getHeight(); // 得到源图长
			if (flag) {// 放大
				width = width * scale;
				height = height * scale;
			} else {// 缩小
				width = width / scale;
				height = height / scale;
			}
			Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
			BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			Graphics g = tag.getGraphics();
			g.drawImage(image, 0, 0, null); // 绘制缩小后的图
			g.dispose();
			ImageIO.write(tag, "JPEG", new File(result));// 输出到文件流
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 图片缩放
	 * 
	 * @param src
	 *            源图像文件地址
	 * @param result
	 *            缩放之后的图像地址
	 * @param height
	 *            缩放之后的高度
	 * @param formatName
	 *            图像格式
	 * @param width
	 *            缩放之后的宽度
	 * @param bb
	 *            比例不对时是否需要补白：true：补白，false: 不补白
	 */
	public static void scale(String src, String result, String formatName, Integer height, Integer width, boolean bb) {

		try {
			double ratio = 1.0;
			File file = new File(src);
			BufferedImage bufferedImage = ImageIO.read(file);
			Image itemp = bufferedImage.getScaledInstance(width, height, bufferedImage.SCALE_SMOOTH);
			// 计算比例
			if (bufferedImage.getHeight() > height || bufferedImage.getWidth() > width) {
				if (bufferedImage.getHeight() > bufferedImage.getWidth()) {
					ratio = (new Integer(height)).doubleValue() / bufferedImage.getHeight();
				} else {
					ratio = (new Integer(width)).doubleValue() / bufferedImage.getWidth();
				}
			}
			if (bufferedImage.getHeight() < height || bufferedImage.getWidth() < width) {
				if (bufferedImage.getHeight() > bufferedImage.getWidth()) {
					ratio = (new Integer(height)).doubleValue() / bufferedImage.getHeight();
				} else {
					ratio = (new Integer(width)).doubleValue() / bufferedImage.getWidth();
				}
			}
			AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
			itemp = op.filter(bufferedImage, null);
			if (bb) {
				BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				Graphics2D graphics2d = image.createGraphics();
				graphics2d.setColor(Color.white);
				graphics2d.fillRect(0, 0, width, height);
				if (width == itemp.getWidth(null)) {
					graphics2d.drawImage(itemp, 0, (height - itemp.getHeight(null)) / 2, itemp.getWidth(null),
							itemp.getHeight(null), Color.white, null);
				} else {
					graphics2d.drawImage(itemp, (height - itemp.getHeight(null)) / 2, 0, itemp.getWidth(null),
							itemp.getHeight(null), Color.white, null);
				}
				graphics2d.dispose();
				itemp = image;
			}
			ImageIO.write((BufferedImage) itemp, formatName, new File(result));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 统一格式,得到图片名称
	 * @param fileName
	 * @return
	 */
	public static String fileNameType(String fileName) {
		String temp[] = fileName.split("\\.");
		String suffix = temp[temp.length-1];
		Integer length2 = fileName.length() - suffix.length();
		String prifix = fileName.substring(0, length2-1);
		fileName = prifix + StringUtil.SUFFIX;			
		return fileName;
	}
	public static void main(String[] args) {
		String src = "C:/Users/gxs/Desktop/tu/TB1AH8cGXXXXXaZXVXXXXXXXXXX_!!0-item_pic.jpg";
		String result = "C:/Users/gxs/Desktop/tu/TB1AH8cGXXXXXaZXVXXXXXXXXXX_!!0-item_pic.jpg";
		String format = "JPG";
		Integer height = 800;
		Integer width = 800;
		Boolean bb = true;
//		scale(src, result, format, height, width, bb);
//		scale(src, result, 2, false);
		
	  // 删除单个文件
//	  String file = "E:/python/cherrypy/imageSearch/upload/6/9/TB1hFHrPpXXXXcGXFXXYXGcGpXX_M2.SS2_430x430q90.jpg";
//	  deleteFile(file);
//	  System.out.println();
	  // 删除一个目录
//	  String dir = "E:/python/cherrypy/imageSearch/upload/6/9";
//	  deleteDirectory(dir);
//	  System.out.println();
	  // 删除文件
//	  dir = "c:/test/test0";
//	  delete(dir);

	}
}
